package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.lightinvesting.api.t2service.LedThreeT2Service;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.baseRelevanted.AuthuserRegbindForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.baseRelevanted.ExtcomacctComuserLeaveForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.baseRelevanted.ModAliasForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.RegForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.AuthuserRegbindVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.IFS.RegisterVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.ModAliasVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.RegBackVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.baseRelevanted.ExtcomacctComuserLeaveVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.AdminBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.back.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.vo.*;
import com.cloudbroker.bcs.platform.ltb.middle.entity.*;
import com.cloudbroker.bcs.platform.ltb.middle.entityview.LeaderListView;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.lightinvesting.LightinvestingService;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.usercenter.UserCenterService;
import com.cloudbroker.bcs.platform.ltb.middle.service.LeaderService;
import com.cloudbroker.bcs.platform.ltb.middle.service.UserService;
import com.cloudbroker.bcs.platform.ltb.middle.util.HttpToBGFormUtil;
import com.cloudbroker.bcs.platform.ltb.middle.util.MD5Util;
import com.cloudbroker.bcs.platform.ltb.middle.util.StringReplacer;
import com.cloudbroker.bcs.platform.ltb.middle.util.UserTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.*;

import static com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes.CommonErr.ALIAS_NAME_CONTAIN_SENSITIVE_WORD;

//import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.CertificateForm;

/**
 * Created by tianrui on 2016/7/14.
 */
@Service
public class AdminUserCenterService implements AdminBizService {

    //用户
    @Resource
    private UserService userService;

    //管理员数据存入中台
    @Resource
    private LeaderService leaderService;

    //调用后台接口
    @Resource
    private LightinvestingService lightinvestingService;
    @Resource
    private LedThreeT2Service ledThreeT2Service;

    @Resource
    private UserCenterService userCenterService;

    private Logger logger = Logger.getLogger(AdminUserCenterService.class);

    /**
     * 投顾创建
     * 1.中台leader注册
     * 2.中台user注册
     * 3.调用后台用户注册
     * 4.调用投顾认证接口
     **/
    @Override
    @Transactional
    public LeaderRegisterBack leader_register(LeaderIDRegForm form)  {
        LeaderRegisterBack leaderRegisterBack = new LeaderRegisterBack();
        if(StringUtils.isNotBlank(form.getInvite_code())) {
            //验证码是否被使用
            UserEntity inviteUser = userService.findByInviteCode(new UserEntity(form.getInvite_code()));
            if (null != inviteUser) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.INVITE_CODE_IS_USED, LeaderRegisterBack.class);
            }
        }
        //投顾没有昵称 只落地真实姓名
        form.setAlias_name(form.getClient_name());
        UserEntity qryUser = new UserEntity();
        qryUser.setMobile(form.getMobile_tel());
        qryUser.setUser_type(String.valueOf(UserType.LEADER.getVal()));
        UserEntity verifyUser = userService.getUserEntity(qryUser);
        //校验投顾是否已注册
        if (null != verifyUser){
            leaderRegisterBack.setUser_id(verifyUser.getUser_id());
            return VOUtil.setSuccessResult(leaderRegisterBack);
        }
        com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.RegisterForm userRegisterForm =
                new com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.RegisterForm();
        userRegisterForm.setLogin_account(form.getMobile_tel());
        userRegisterForm.setAuth_password(MD5Util.encrypt(form.getPassword()));
        userRegisterForm.setUser_type("2");
        userRegisterForm.setTenant_id(form.getCompany_id());
        userRegisterForm.setAlias_name(form.getAlias_name());
        userRegisterForm.setRegister_flag("2");
        userRegisterForm.setMobile(form.getMobile_tel());
        userRegisterForm.setBranch_no(form.getBranch_no()+"");
        RegisterVo userT2RegBack = userCenterService.func_register(userRegisterForm);
        if(!"0".equals(userT2RegBack.getError_no()) && !"10003".equals(userT2RegBack.getError_no())){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return VOUtil.genErrorResult(userT2RegBack.getError_no(),userT2RegBack.getError_info(), LeaderRegisterBack.class);
        }
        Leader leader = new Leader(form.getAlias_name(), form.getMobile_tel(),
                System.currentTimeMillis(), form.getCompany_id());
        leader.setJob_state(LeaderJobStateType.ON.getVal());
        getLeaderByIDApplyForm(leader, form);
        leaderService.addLeader(leader);
        //注册到ITN
        AuthuserRegbindForm authuserRegbindForm = new AuthuserRegbindForm();
        authuserRegbindForm.setBusinsys_no(Long.valueOf(1001));
        authuserRegbindForm.setSendercomp_id(form.getSendercomp_id());
        authuserRegbindForm.setMobile_tel(form.getMobile_tel());
        String user_key = form.getUser_name() + MD5Util.encrypt(form.getAdmin_password()) +
                form.getSendercomp_id() + form.getCompany_id();
        authuserRegbindForm.setUser_token(UserTokenUtil.getAdminUserToken(user_key));
        AuthuserRegbindVo authuserRegbindVo = new AuthuserRegbindVo();
        try {
            authuserRegbindVo = lightinvestingService.func_services_authuser_regbind(authuserRegbindForm);
        }catch (Exception e){
            //成功与否不要影响注册流程
            e.printStackTrace();
        }
        if (authuserRegbindVo == null || authuserRegbindVo.getUser_id() == null){
            authuserRegbindVo.setUser_id("0");
        }
        long leader_id = leader.getLeader_id();
        UserEntity userEntity = new UserEntity();
        userEntity.setUser_id(Long.parseLong(userT2RegBack.getUser_id()));
        userEntity.setSendercomp_id(form.getSendercomp_id());
        userEntity.setCompany_id(form.getCompany_id());
        userEntity.setAccounts_id(leader_id);
        userEntity.setPassword(MD5Util.encrypt(form.getPassword()));
        userEntity.setUser_name(form.getMobile_tel());
        userEntity.setUser_type(String.valueOf(UserType.LEADER.getVal()));
        userEntity.setUser_status(String.valueOf(UserStatus.WAITAUTH.getVal()));
        userEntity.setAlias_name(form.getAlias_name());
        userEntity.setMobile(form.getMobile_tel());
        userEntity.setInvite_code(form.getInvite_code());
        userService.addUser(userEntity);
        leaderRegisterBack.setUser_id(userEntity.getUser_id());
        return BgLeaderRegister(form, leaderRegisterBack.getUser_id());
    }

    /**
     * 中台投顾注册
     * */
    private boolean MiddleLeaderRegister(LeaderIDRegForm form, LeaderRegisterBack leaderRegisterBack){
        UserEntity qryUser = new UserEntity();
        qryUser.setMobile(form.getMobile_tel());
        //投顾校验重复性只校验手机号
//        qryUser.setCompany_id(form.getCompany_id());
//        qryUser.setSendercomp_id(form.getSendercomp_id());
        qryUser.setUser_type(String.valueOf(UserType.LEADER.getVal()));
        UserEntity verifyUser = userService.getUserEntity(qryUser);
        //校验投顾是否已注册
        if (null != verifyUser){
            leaderRegisterBack.setUser_id(verifyUser.getUser_id());
            return false;
        }
        com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.RegisterForm userRegisterForm =
                new com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.RegisterForm();
        userRegisterForm.setLogin_account(form.getMobile_tel());
        userRegisterForm.setAuth_password(MD5Util.encrypt(form.getPassword()));
        userRegisterForm.setUser_type("2");
        userRegisterForm.setTenant_id(form.getCompany_id());
        userRegisterForm.setAlias_name(form.getAlias_name());
        userRegisterForm.setRegister_flag("2");
        RegisterVo userT2RegBack = userCenterService.func_register(userRegisterForm);
        if(!"0".equals(userT2RegBack.getError_no())&& !"10003".equals(userT2RegBack.getError_no())){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return VOUtil.genErrorResult(userT2RegBack.getError_no(),userT2RegBack.getError_info(), UserLoginBack.class);
            throw new RuntimeException(userT2RegBack.getError_no() + "|" + userT2RegBack.getError_info());
        }
        Leader leader = new Leader(form.getAlias_name(), form.getMobile_tel(),
                System.currentTimeMillis(), form.getCompany_id());
        leader.setJob_state(LeaderJobStateType.ON.getVal());
        getLeaderByIDApplyForm(leader, form);
        leaderService.addLeader(leader);
        //注册到ITN
        AuthuserRegbindForm authuserRegbindForm = new AuthuserRegbindForm();
        authuserRegbindForm.setBusinsys_no(Long.valueOf(1001));
        authuserRegbindForm.setSendercomp_id(form.getSendercomp_id());
        authuserRegbindForm.setMobile_tel(form.getMobile_tel());
        String user_key = form.getUser_name() + MD5Util.encrypt(form.getAdmin_password()) +
                form.getSendercomp_id() + form.getCompany_id();
        authuserRegbindForm.setUser_token(UserTokenUtil.getAdminUserToken(user_key));
        AuthuserRegbindVo authuserRegbindVo = new AuthuserRegbindVo();
        try {
//            authuserRegbindVo = lightinvestingService.func_authuser_regbind(authuserRegbindForm);
            authuserRegbindVo = lightinvestingService.func_services_authuser_regbind(authuserRegbindForm);
        }catch (Exception e){
            //成功与否不要影响注册流程
            e.printStackTrace();
        }
        if (authuserRegbindVo == null || authuserRegbindVo.getUser_id() == null){
            authuserRegbindVo.setUser_id("0");
        }
        long leader_id = leader.getLeader_id();
        UserEntity userEntity = new UserEntity();
        userEntity.setUser_id(Long.parseLong(userT2RegBack.getUser_id()));
        userEntity.setSendercomp_id(form.getSendercomp_id());
        userEntity.setCompany_id(form.getCompany_id());
        userEntity.setAccounts_id(leader_id);
        userEntity.setPassword(MD5Util.encrypt(form.getPassword()));
        userEntity.setUser_name(form.getMobile_tel());
        userEntity.setUser_type(String.valueOf(UserType.LEADER.getVal()));
        userEntity.setUser_status(String.valueOf(UserStatus.WAITAUTH.getVal()));
        userEntity.setAlias_name(form.getAlias_name());
        userEntity.setMobile(form.getMobile_tel());
        userEntity.setInvite_code(form.getInvite_code());
//        userEntity.setCif_id(Long.valueOf(authuserRegbindVo.getAuth_id()));
        userService.addUser(userEntity);
        leaderRegisterBack.setUser_id(userEntity.getUser_id());
        return true;
    }

    /**
     * 后台注册
     * */
    private LeaderRegisterBack BgLeaderRegister(LeaderIDRegForm form, long user_id){
        LeaderRegisterBack leaderRegisterBack = new LeaderRegisterBack();
        leaderRegisterBack.setUser_id(user_id);
        UserEntity userEntity = userService.getUserEntity(new UserEntity(user_id));
        RegForm regForm = HttpToBGFormUtil.registFormSwap(form);
        regForm.setUser_id(String.valueOf(user_id));
        String user_key = form.getUser_name() + MD5Util.encrypt(form.getAdmin_password()) +
                form.getSendercomp_id() + form.getCompany_id();
        regForm.setUser_token(UserTokenUtil.getAdminUserToken(user_key));
        RegBackVo regBackVo =  lightinvestingService.func_register_authuser(regForm);
        if (regBackVo.getSerial_no() == null){
            logger.error("bg Server register failed errono:" + regBackVo.getError_no() +
                    "errInfo:" + regBackVo.getError_info());
//            throw new RuntimeException(regBackVo.getError_no() + "|" + regBackVo.getError_info());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return VOUtil.genBGErrorResult(regBackVo.getError_no(),regBackVo.getError_info(), LeaderRegisterBack.class);
        }
        //投顾认证不做处理返回管理端user_id
//        InterestCertForm interestCertForm = HttpToBGFormUtil.leaderIDApplyFormSwap(form);
//        InterestCertVo interestCertVo = lightinvestingService.func_interest_cert__add(interestCertForm);
//        if (interestCertVo.getSerial_no() != 0){
//            return VOUtil.genErrorResultVo(BG_LEADER_AUTHEN_FAILED);
//        }
        return VOUtil.setSuccessResult(leaderRegisterBack);
    }

    /**
     * 投顾信息完善
     * */
    private void getLeaderByIDApplyForm(Leader leader, LeaderIDRegForm form) {
        leader.setProfile(form.getBackground_info());
        leader.setJob_title(form.getJob_title());
        leader.setSex(form.getSex());
        leader.setQq(form.getQq());
        leader.setProfile(form.getBackground_info());
        leader.setId_no(form.getId_no());
        leader.setCertificate_id(form.getQualify_no());
    }

    @Override
    public UserQueryListBack user_query_list(AdminUserListQueryForm form) {
        List<AdminUserIdList> list = JSONArray.parseArray(form.getData_list(),AdminUserIdList.class);
        if(list==null || list.size() ==0){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.AdminErrorInfo.USER_QUERY_LIST_EMPTY,UserQueryListBack.class);
        }
        List<LeaderListView> leader_list = leaderService.queryLeaderList(list);
        List<UserQueryListData> data_list = new ArrayList<>(leader_list.size());
        for(LeaderListView l : leader_list){
            UserQueryListData temp = new UserQueryListData();
            temp.setUser_id(l.getUser_id());
            temp.setJob_state(l.getJob_state());
            temp.setWx_public_account(l.getWx_public_account());
            data_list.add(temp);
        }
        UserQueryListBack back = new UserQueryListBack();
        back.setData_str(JSON.toJSONString(data_list));
        UserQueryListBack e = VOUtil.setSuccessResult(back);
        return e;
    }

    @Override
    public LeaderUpdateJobStateBack leader_update_job_state(LeaderUpdateJobStateForm form) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUser_id(Long.valueOf(form.getUser_id()));
        UserEntity entity = userService.getUserEntity(userEntity);
        if(entity == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NOT_EXIT,LeaderUpdateJobStateBack.class);
        }
        Leader temp = new Leader();
        temp.setLeader_id(Long.valueOf(entity.getAccounts_id()));
        Leader leader = leaderService.getLeader(temp);
        if(leader==null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NOT_EXIT,LeaderUpdateJobStateBack.class);
        }
        if(leader.getJob_state().equals(LeaderJobStateType.ON.getVal())){
            leader.setJob_state(LeaderJobStateType.OFF.getVal());
        }else{
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.LEADER_LEAVE,LeaderUpdateJobStateBack.class);
        }
        ExtcomacctComuserLeaveForm extcomacctComuserLeaveForm = new ExtcomacctComuserLeaveForm();
        extcomacctComuserLeaveForm.setAdviser_id(form.getUser_id());
        extcomacctComuserLeaveForm.setSendercomp_id(form.getCompany_id());
        ExtcomacctComuserLeaveVo extcomacctComuserLeaveVo = ledThreeT2Service.func_extcomacct_comuser_leave(extcomacctComuserLeaveForm);
        if(!VOUtil.isSuccess(extcomacctComuserLeaveVo)){
            return VOUtil.genBGErrorResult(extcomacctComuserLeaveVo.getError_no(),extcomacctComuserLeaveVo.getError_info(),LeaderUpdateJobStateBack.class);
        }
        leaderService.updateLeaderJobState(leader);
        return VOUtil.setSuccessResult(new LeaderUpdateJobStateBack());
    }

    @Override
    public LeaderResetPwdBack leader_reset_password(LeaderResetPwdForm form) {
        UserEntity temp = new UserEntity();
        temp.setUser_id(Long.valueOf(form.getUser_id()));
        UserEntity userEntity = userService.getUserEntity(temp);
        if(userEntity == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NOT_EXIT,LeaderResetPwdBack.class);
        }
        userEntity.setPassword(MD5Util.encrypt(form.getPassword()));
        userService.updatePassword(userEntity);
        return VOUtil.setSuccessResult(new LeaderResetPwdBack());
    }

    @Override
    @Transactional
    public LeaderUpdateAliasName func_leader_update_alias_name(LeaderUpdateAliasNameForm form) {
        //敏感词过滤
        if (StringReplacer.hasSensitiveWord(form.getAlias_name(), form.getCompany_id())){
            return VOUtil.genErrorResult(ALIAS_NAME_CONTAIN_SENSITIVE_WORD, LeaderUpdateAliasName.class);
        }
        //投顾昵称修改
//        Leader leader = new Leader();
//        leader.setAlias_name(form.getAlias_name());
//        leader.setLeader_id(form.getUser().getAccounts_id());
//        leaderService.updateLeaderAliasName(leader);
        UserEntity userEntity = new UserEntity();
        userEntity.setAlias_name(form.getAlias_name());
        userEntity.setUser_id(Long.valueOf(form.getUser().getUser_id()));
        userService.updateUserAliasName(userEntity);
//        UserTokenUtil.updateByUpdateKey(form.getUser_token(), form.getAlias_name(), UserCacheFreshType.UPDATE_ALIAS);
        ModAliasForm modAliasForm = new ModAliasForm();
        modAliasForm.setAlias_name(form.getAlias_name());
        modAliasForm.setUser_id(String.valueOf(userEntity.getUser_id()));
        modAliasForm.setSendercomp_id(form.getSendercomp_id());
        modAliasForm.setUser_token(form.getUser_token());
        modAliasForm.setNeed_user_id("1");
        ModAliasVo modAliasVo = lightinvestingService.func_alias_mod(modAliasForm);
        if (modAliasVo.getSerial_no() == null){
            return VOUtil.genBGErrorResult(modAliasVo.getError_no(),
                    modAliasVo.getExt_error_info(), LeaderUpdateAliasName.class);
        }
        return VOUtil.setSuccessResult(new LeaderUpdateAliasName());
    }

    public static void main(String[] args) {
        String s = new String();
        s.equals("");
        Long a = new Long(11111);
        System.out.println(a.equals(11111));
    }

}